package com.example.woke;

import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.bean.AreaCode;
import com.bean.BankBranchCode;
import com.bean.BaseResponse;
import com.bean.CountyAreaCode;
import com.bean.IndustryCategories;
import com.http.HttpMethods;
import com.jakewharton.rxbinding2.view.RxView;
import com.woke.adapter.OnItemClickListener;
import com.woke.fragment.BankBranchDialogFragment;
import com.woke.fragment.IndustrySelecteDialogFragment;
import com.woke.fragment.ProvincesAndCitiesDialogFragment;
import com.woke.method.MyApp;
import com.woke.method.NetworkUtils;
import com.woke.serizedatas.Datas_load;

import com.zhongcai.online.BR;
import com.zhongcai.online.R;

import com.zhongcai.online.databinding.ActivityPuFaMerchantsInBinding;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.xl.xxl.tools.CommonUtil;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * 商户入驻
 */
public class PuFaMerchantsInActivity extends AppCompatActivity {

    private Handler mHandle = new Handler();
    private ActivityPuFaMerchantsInBinding mBinding;
    private MyApp myApp;
    private int pageInde = 0;
    private int mIndustrId = 1;//行业类行  1实体 2虚拟
    private IndustrySelecteDialogFragment mIndustrySelecteDialogFragment;//行业列表
    private ProvincesAndCitiesDialogFragment mProvincesAndCitiesDialogFragment;//省市
    private IndustryCategories mIndustryCategory; //所选行业
    private BankBranchCode mBankBranchCode;  //所选开户支行
    private AreaCode mMerchantsProvince, mMerchantsCity, mBankBelongingProvince, mBankBelongingCity;//省市
    private CountyAreaCode mCountyAreaCode;
    private View mTempAreaView;  //临时 省市V
    private BankBranchDialogFragment mBranchDialogFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//		setContentView (R.layout.activity_merchants_in);
        myApp = MyApp.getInstance();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_pu_fa_merchants_in);
        mBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pageInde > 1) {
                    mBinding.secondViewSwitcher.showPrevious();
                    pageInde--;
                } else if (pageInde > 0) {
                    mBinding.viewSwitcher.showPrevious();
                    pageInde--;
                } else {
                    finish();
                }
            }
        });
        mBinding.setVariable(BR.base_list_title, getResources().getString(R.string.title_activity_pufa_merchants_in));

        initData();
        final String[] mIndustrIdValues = getResources().getStringArray(R.array.pu_fa_business_type);
        ArrayAdapter mBusinessTypedapter = new ArrayAdapter<String>(this, R.layout.spinner_item, R.id.textView, mIndustrIdValues);
        mBusinessTypedapter.setDropDownViewResource(R.layout.spinner_item_drop);
        mBinding.merchantsInPaymentWaySpinner.setAdapter(mBusinessTypedapter);
        mBinding.merchantsInPaymentWaySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {


            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                //商户类型
                mIndustrId = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        RxView.clicks(mBinding.industryCategoriesTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //选择行业类别
                getIndustryCategories();
            }
        });
        RxView.clicks(mBinding.provincesAndCitiesTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //商户省市  选择行省市
                mTempAreaView = mBinding.provincesAndCitiesTv;
                chooseProvincesAndCities(true);
            }
        });
        RxView.clicks(mBinding.bankBelongingTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //开户行省市  选择行省市
                mTempAreaView = mBinding.bankBelongingTv;
                chooseProvincesAndCities(false);
            }
        });
        RxView.clicks(mBinding.bankNameTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //选择开户支行
                chooseBankBranch();
            }
        });

        RxView.clicks(mBinding.nextBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //下一步
                String merchantName = mBinding.merchantNameEd.getText().toString();//商户名称
                String merchantShortName = mBinding.merchantShortNameEd.getText().toString();//商户简称
                String merchantAddress = mBinding.merchantAddressEd.getText().toString();//商户地址
                if (TextUtils.isEmpty(merchantName)) {
                    showToast(getResources().getString(R.string.hint_merchants_name));
                    return;
                }
                if (TextUtils.isEmpty(merchantShortName)) {
                    showToast(getResources().getString(R.string.hint_merchants_short_name2));
                    return;
                }
                if (mIndustryCategory == null) {
                    showToast(getResources().getString(R.string.hint_selecte_business_categories));
                    return;
                }
                if (mCountyAreaCode==null) {
                    showToast(getResources().getString(R.string.hint_selecte_business_provinces));
                    return;
                }
                if (TextUtils.isEmpty(merchantAddress)) {
                    showToast(getResources().getString(R.string.hint_merchants_address));
                    return;
                }
                if (!NetworkUtils.isConnected(PuFaMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }
                pageInde++;
                mBinding.viewSwitcher.showNext();
            }
        });
        RxView.clicks(mBinding.middleNextBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //下一步

                String legalPersonName = mBinding.enterpriseLegalPersonEd.getText().toString();//企业法人
                String email = mBinding.emailEd.getText().toString();//邮箱
                String service_tel = mBinding.merchantPhoneEd.getText().toString();//客服电话
                String contactName = mBinding.merchantContactNameEd.getText().toString();//负责人姓名
                String contactPhone = mBinding.merchantContactPhoneEd.getText().toString();//负责人手机
                String idCardContact = mBinding.principalIdcardEd.getText().toString();//负责人身份证

                if (TextUtils.isEmpty(legalPersonName)) {
                    showToast(getResources().getString(R.string.hint_enterprise_legal_person_name));
                    return;
                }
                if (TextUtils.isEmpty(email) || !CommonUtil.isEmail(email)) {
                    showToast(getResources().getString(R.string.hint_email_not_null));
                    return;
                }
                if (TextUtils.isEmpty(service_tel)) {
                    showToast(getResources().getString(R.string.hint_merchants_phone));
                    return;
                }
                if (TextUtils.isEmpty(contactName)) {
                    showToast(getResources().getString(R.string.hint_merchants_contact_name));
                    return;
                }
                if (!CommonUtil.isPhoneNo(contactPhone)) {
                    showToast(getResources().getString(R.string.hint_phone_not_null));
                    return;
                }
                if (TextUtils.isEmpty(idCardContact) || idCardContact.length() < 14) {
                    showToast(getResources().getString(R.string.hint_id_card_length));
                    return;
                }

                if (!NetworkUtils.isConnected(PuFaMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }
                pageInde++;
                mBinding.secondViewSwitcher.showNext();
            }
        });
        RxView.clicks(mBinding.commitBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //提交商户入驻信息

                String bankAccout = mBinding.merchantsBankAccountEd.getText().toString();    //银行卡号
                String bankCardPhone = mBinding.cardPhoneEd.getText().toString();           //银行预留手机号
                String bankCardHolderName = mBinding.merchantsBankAccountNameEd.getText().toString();  //持卡人姓名
                String bankCardHolderIdCard = mBinding.merchantsIdcardEd.getText().toString();     //持卡人身份证

                if (TextUtils.isEmpty(bankAccout)) {
                    showToast(getResources().getString(R.string.hint_merchants_bank_account));
                    return;
                }
                if (!CommonUtil.isPhoneNo(bankCardPhone)) {
                    showToast(getResources().getString(R.string.hint_phone_not_null));
                    return;
                }
                if (TextUtils.isEmpty(bankCardHolderName)) {
                    showToast(getResources().getString(R.string.hint_merchants_bank_account_name));
                    return;
                }
                if (TextUtils.isEmpty(bankCardHolderIdCard)) {
                    showToast(getResources().getString(R.string.hint_id_card_length));
                    return;
                }

                if (mBankBranchCode == null) {
                    //开户支行
                    showToast(getResources().getString(R.string.hint_bank_name_select));
                    return;
                }

                if (mBankBelongingProvince == null || mBankBelongingCity == null) {
                    //开户行省市
                    showToast(getResources().getString(R.string.hint_bank_name_select));
                    return;
                }

                if (!NetworkUtils.isConnected(PuFaMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }


                String merchantName = mBinding.merchantNameEd.getText().toString();//商户名称
                String merchantShortName = mBinding.merchantShortNameEd.getText().toString();//商户简称
                String merchantAddress = mBinding.merchantAddressEd.getText().toString();//商户地址


                String legalPersonName = mBinding.enterpriseLegalPersonEd.getText().toString();//企业法人
                String email = mBinding.emailEd.getText().toString();//邮箱
                String service_tel = mBinding.merchantPhoneEd.getText().toString();//客服电话
                String contactName = mBinding.merchantContactNameEd.getText().toString();//负责人姓名
                String contactPhone = mBinding.merchantContactPhoneEd.getText().toString();//负责人手机
                String idCardContact = mBinding.principalIdcardEd.getText().toString();//负责人身份证


                Datas_load load = myApp.getDatas_load();
                if (load != null) {
                    String userId = load.getId();
                    if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {

                        Log.e("111", "----" + userId);
                        Map<String, String> params = new HashMap<>();
                        params.put("userId", userId);
                        params.put("merchantName", merchantName);
                        params.put("merchantShortName", merchantShortName);
                        params.put("mchDealType", String.valueOf(mIndustrId));
                        params.put("industrId", String.valueOf(mIndustryCategory.getIndustrid()));
                        params.put("province", mCountyAreaCode.getPro_code());
                        params.put("city", mCountyAreaCode.getCity_code());
                        params.put("county", mCountyAreaCode.getCounty_code());
                        params.put("address", merchantAddress);

                        params.put("legalPerson", legalPersonName);
                        params.put("email", email);
                        params.put("customerPhone", service_tel);
                        params.put("principal", contactName);
                        params.put("principalMobile", contactPhone);
                        params.put("idCode", idCardContact);

                        params.put("accountCode", bankAccout);
                        params.put("tel", bankCardPhone);
                        params.put("accountName", bankCardHolderName);
                        params.put("idCard", bankCardHolderIdCard);
                        params.put("bankId", mBankBranchCode.getBankid());
                        params.put("bankName", mBankBranchCode.getBranchname());
                        params.put("contactLine", mBankBranchCode.getLinenum());
                        params.put("bprovince", mBankBelongingCity.getP_areacode());
                        params.put("bcity", mBankBelongingCity.getAreacode());
                        Log.e("222", params.toString());
                        HttpMethods.getInstance().puFaMerchantsEnter(mCommitObserver, params);
                    }
                }
            }
        });
    }

    private void initData() {
        Datas_load load = MyApp.getInstance().getDatas_load();
        if (load != null) {
            //联系人电话号码
            mBinding.merchantContactPhoneEd.setText(load.getUser_login());
            //银行持卡人手机号
            mBinding.cardPhoneEd.setText(load.getUser_login());
            //身份证号
            if (!TextUtils.isEmpty(load.getUser_no()) && load.getUser_no().length() >= 15) {
                mBinding.merchantsIdcardEd.setText(load.getUser_no());
            }
//            if(){}
            //银行卡卡号
            mBinding.merchantsBankAccountEd.setText(load.getCard_no());
            //开户行
//            mBinding.bankNameEd.setText(load.getBank_name());
        }
//        UserInfo userInfo = mRealm.where(UserInfo.class)
//                .equalTo("id", getLocalUserId(this))
//                .findFirst();
//        if (userInfo != null) {
//            //联系人电话号码
//            mBinding.merchantContactPhoneEd.setText(userInfo.getUser_login());
//            //身份证号
//            mBinding.merchantIdcardEd.setText(userInfo.getUser_no());
//            //银行卡卡号
//            mBinding.merchantsBankAccountEd.setText(userInfo.getCard_no());
//            //开户行
//            mBinding.bankNameEd.setText(userInfo.getBank_name());
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (pageInde > 1) {
                mBinding.secondViewSwitcher.showPrevious();
                pageInde--;
                return false;
            } else if (pageInde > 0) {
                mBinding.viewSwitcher.showPrevious();
                pageInde--;
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);

    }

    /**
     * 浦发行业列表
     *
     * @param list
     */
    private void chooseIndustry(List<IndustryCategories> list) {
        if (list != null && list.size() > 0) {
            if (mIndustrySelecteDialogFragment == null) {
                mIndustrySelecteDialogFragment = new IndustrySelecteDialogFragment();
                mIndustrySelecteDialogFragment.setOnItemClickListener(mItemClickListener);
            }
            mIndustrySelecteDialogFragment.setItems(list);
            mIndustrySelecteDialogFragment.show(getSupportFragmentManager(), "IndustryCategories");
        }
    }

    /**
     * 选择省市
     */
    private void chooseProvincesAndCities(boolean isNeedCoutyCode) {
        if (NetworkUtils.isConnected(this)) {
            if (mProvincesAndCitiesDialogFragment == null) {
                mProvincesAndCitiesDialogFragment = new ProvincesAndCitiesDialogFragment();
                mProvincesAndCitiesDialogFragment.setOnItemClickListener(mItemClickListener);
            }
            mProvincesAndCitiesDialogFragment.needCountyCode(isNeedCoutyCode);
            mProvincesAndCitiesDialogFragment.show(getSupportFragmentManager(), "ProvincesAndCities");
        } else {
            showToast(getResources().getString(R.string.error_net2));
        }
    }

    /**
     * 选择支行
     */
    private void chooseBankBranch() {
        if (mBranchDialogFragment == null) {
            mBranchDialogFragment = new BankBranchDialogFragment();
            mBranchDialogFragment.setOnItemClickListener(mItemClickListener);
        }
        mBranchDialogFragment.show(getSupportFragmentManager(), "BranchDialogFragment");
    }

    private OnItemClickListener mItemClickListener = new OnItemClickListener() {

        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof IndustryCategories) {
                //行业类别
                if (mIndustrySelecteDialogFragment != null) {
                    mIndustrySelecteDialogFragment.dismiss();
                }
                mIndustryCategory = (IndustryCategories) object;
                mBinding.industryCategoriesTv.setText(mIndustryCategory.getName());
            } else if (object instanceof AreaCode) {
                AreaCode areaCode = (AreaCode) object;
                if (mTempAreaView != null) {
                    if (mTempAreaView.getId() == mBinding.provincesAndCitiesTv.getId()) {
                        //商户所在省市
//                        if (areaCode.isProvinceCode()) {
//                            //省
//                        } else {
//                            //市
//                            if (mProvincesAndCitiesDialogFragment != null) {
//                                mMerchantsProvince = mProvincesAndCitiesDialogFragment.getProvinceAreaCode();
//                                mMerchantsCity = mProvincesAndCitiesDialogFragment.getCityAreaCode();
//                                String tempStr = mMerchantsProvince.getName() + mMerchantsCity.getName();
//                                mBinding.provincesAndCitiesTv.setText(tempStr);
//                            }
//                        }
                    } else if (mTempAreaView.getId() == mBinding.bankBelongingTv.getId()) {
                        //开户行所在省市
                        if (areaCode.isProvinceCode()) {
                            //省
                        } else {
                            //市
                            if (mProvincesAndCitiesDialogFragment != null) {
                                mBankBelongingProvince = mProvincesAndCitiesDialogFragment.getProvinceAreaCode();
                                mBankBelongingCity = mProvincesAndCitiesDialogFragment.getCityAreaCode();
                                String tempStr = mBankBelongingProvince.getName() + mBankBelongingCity.getName();
                                mBinding.bankBelongingTv.setText(tempStr);
                            }
                        }
                    }
                }
            } else if (object instanceof CountyAreaCode) {
                CountyAreaCode countyAreaCode = (CountyAreaCode) object;
                if (mProvincesAndCitiesDialogFragment != null) {
                    mMerchantsProvince = mProvincesAndCitiesDialogFragment.getProvinceAreaCode();
                    mMerchantsCity = mProvincesAndCitiesDialogFragment.getCityAreaCode();
                    mCountyAreaCode=countyAreaCode;
                    String tempStr = countyAreaCode.getPro_name()+countyAreaCode.getCity_name()+countyAreaCode.getCounty_name();
                    mBinding.provincesAndCitiesTv.setText(tempStr);
                }
            } else if (object instanceof BankBranchCode) {
                mBankBranchCode = (BankBranchCode) object;
                mBinding.bankNameTv.setText(mBankBranchCode.getBranchname());
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

//    private void commit() {
//
//        //商户名称
//        String merchantName = mBinding.merchantNameEd.getText().toString().trim();
//        //商户简写
//        String merchantShortName = mBinding.merchantShortNameEd.getText().toString().trim();
//        //商户地址
//        String merchantAddress = mBinding.merchantAddressEd.getText().toString().trim();
//        //客服电话
//        String servicePhone = mBinding.merchantPhoneEd.getText().toString().trim();
//        //联系人姓名
//        String contactName = mBinding.merchantContactNameEd.getText().toString().trim();
//        //联系人手机号
//        String contactPhone = mBinding.merchantContactPhoneEd.getText().toString().trim();
//        //身份证
//        String idCard = mBinding.merchantIdcardEd.getText().toString().trim();
//        //银行卡
//        String bankAccount = mBinding.merchantsBankAccountEd.getText().toString().trim();
//        //银行卡人姓名
//        String bankAccountName = mBinding.merchantsBankAccountNameEd.getText().toString().trim();
//        //开户行
////        String bankName = mBinding.bankNameEd.getText().toString().trim();
//
//        if (TextUtils.isEmpty(merchantName)) {
//            showToast("商户名称不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(merchantShortName)) {
//            showToast("商户简称名称不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(merchantAddress)) {
//            showToast("商户地址不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(servicePhone)) {
//            showToast("客服电话不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(contactName)) {
//            showToast("姓名不能为空");
//            return;
//        }
//        if (!CommonUtil.isPhoneNo(contactPhone)) {
//            showToast("输入正确的11位手机号码");
//            return;
//        }
//        if (TextUtils.isEmpty(idCard) && idCard.length() > 10) {
//            showToast("身份证不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(bankAccount)) {
//            showToast("银行卡号不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(bankAccountName)) {
//            showToast("真实姓名不能为空");
//            return;
//        }
////        if (TextUtils.isEmpty(bankName)) {
////            showToast("开户行不能为空");
////            return;
////        }
//        Datas_load load = myApp.getDatas_load();
//        if (load != null) {
//            String userId = load.getId();
//            if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {
//
//
//            } else {
//                showToast("您还未登录");
//            }
//        }
//    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private Observer<BaseResponse> mCommitMerchantsObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {

            if (value != null) {
                if (value.resultSuccess()) {
                    showToast(value.getInfo());
                    mHandle.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 500);
                } else {
                    showToast(value.getInfo());
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                showToast(e.getMessage());
            }
        }

        @Override
        public void onComplete() {

        }
    };

    private List<IndustryCategories> mIndustryCategoriesList = new ArrayList<>();

    private void getIndustryCategories() {
        if (mIndustryCategoriesList.size() == 0) {
            if (NetworkUtils.isConnected(this)) {
                HttpMethods.getInstance().getIndustryCategories(mIndustryListObserver);
            } else {
                showToast(getResources().getString(R.string.error_net2));
            }
        } else {
            chooseIndustry(mIndustryCategoriesList);
        }
    }

    private Observer<List<IndustryCategories>> mIndustryListObserver = new Observer<List<IndustryCategories>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<IndustryCategories> value) {
            if (value != null && value.size() > 0) {
                mIndustryCategoriesList.clear();
                mIndustryCategoriesList.addAll(value);
                chooseIndustry(mIndustryCategoriesList);
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private Observer<BaseResponse> mCommitObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null) {
                if (value.resultSuccess()) {
                    new AlertDialog.Builder(PuFaMerchantsInActivity.this).setTitle("提交成功").setMessage(R.string.pufa_merchants_in_auth_ing).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).create().show();
                } else {
                    showToast(value.getInfo());
                }
                Log.e("onNext", "----" + value.getInfo());
            }
        }

        @Override
        public void onError(Throwable e) {
            Log.e("222", "----onError");
            if (e != null) {
                Log.e("222", "----onError==" + e.getMessage());
            }
        }

        @Override
        public void onComplete() {

        }
    };

}
